<template>
  <div class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <SearchFrame
        btnName="添加文章"
        :hasPermi="['logic:article:add']"
        :btnFunc="handleAddOrEdit"
        :model="queryParams"
        :search-func="handleQuery"
        :reset="resetQuery"
      >
        <SearchFrameItem prop="categoryId">
          <el-select v-model="queryParams.categoryId" filterable placeholder="请选择文章分类" style="width: 100%" clearable>
            <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"> </el-option>
          </el-select>
        </SearchFrameItem>
        <SearchFrameItem prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable />
        </SearchFrameItem>
      </SearchFrame>
    </transition>
    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" class-name="num" align="left" width="120">
        <template #default="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="文章名称" align="left" prop="title" show-overflow-tooltip />
      <el-table-column label="分类" align="left" prop="categoryName" show-overflow-tooltip />
      <el-table-column label="浏览量" align="left" prop="visitCount" show-overflow-tooltip> </el-table-column>
      <el-table-column label="状态" align="left" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @change="toggleStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="left" prop="publishTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleAddOrEdit(scope.row.articleId)" v-hasPermi="['logic:article:edit']">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" v-hasPermi="['logic:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup lang="ts" name="ArticleNew">
import { listArticle, getArticle, delArticle, addArticle, updateArticle, changeStatus } from '@/api/logic/article';
import { listArticleCategory } from '@/api/logic/articleCategory';
import { ArticleVO, ArticleQuery, ArticleForm } from '@/api/logic/article/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logic_language_type, logic_isactive } = toRefs<any>(proxy?.useDict('logic_language_type', 'logic_isactive'));

const route = useRoute();
const router = useRouter();

const articleList = ref<ArticleVO[]>([]);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<ArticleForm, ArticleQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: '',
    title: '',
  },
});

const { queryParams } = toRefs(data);

/** 查询文章管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listArticle(queryParams.value);
  res.rows.forEach(el => el.status = !!(el.isActive))
  articleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageSize = 10;
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ArticleVO[]) => {
  ids.value = selection.map(item => item.articleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增及修改按钮操作 */
const handleAddOrEdit = async (id: string) => {
  router.push({
    path: '/workspace/addOrEditArticle',
    query: {
      articleId: id || ''
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (row?: ArticleVO) => {
  const _articleIds = row?.articleId || ids.value;
  await proxy?.$modal.confirm('确认要删除改该文章吗？').finally(() => loading.value = false);
  await delArticle(_articleIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
// 修改状态操作
const toggleStatus = async (row) => {
  try {
    const res = await changeStatus({ articleId: row.articleId, isActive: row.isActive ? 0 : 1 })
    proxy?.$modal.msgSuccess(res.msg);
    getList()
  } catch (e) {
    console.log(e)
  }
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('logic/article/export', {
    ...queryParams.value
  }, `article_${new Date().getTime()}.xlsx`)
}

// 获取文章分类下拉查询项
const categoryList = ref()
const getCategoryList =  async() => {
  try {
    const res = await listArticleCategory({isActive: 1});
    categoryList.value = res.rows
  } catch (error) {
    categoryList.value = []
  }
}
onMounted(() => {
  getList();
  getCategoryList()
});
onActivated(() => {
  getList();
  getCategoryList()
});
</script>
